
var g_last_response = null;
var login_error = {};
login_error[-1] = '重复登录';
login_error[-2] = '用户名或密码为空';
login_error[-3] = '用户不存在或者密码错误';

var g_client_key = null;
var g_server = 'http://www.wayixia.com';

function AddImage() {
  return function() {
	if(Q.$('login-area').style.display == '') {
	  ajax_login();
	} else {
	  // Tell the background page to add the image
	  // get data from form 
	  if(!g_last_response) {
		alert('image is not found');
		CloseDialog(true);
		return true;
	  }
      ajax_wa();
	}	  
  }  
}

function ajax_login() {
  // 处理用户登录
  var username = Q.$('login-name').value;
  var userpwd = Q.$('login-pwd').value;

  Q.Ajax({
    command: g_server+'?app=wayixia&mod=user&action=do-login&inajax=true',
    data: {name: username, pwd: userpwd },
    oncomplete : function(xmlhttp) {
      // console.log(xmlhttp.responseText);
      var resp = JSON.parse(xmlhttp.responseText);
      if(resp && resp.header == 0) {
        // 登录成功
		Q.$('login-area').style.display = 'none';
		Q.$('image-area').style.display = '';
		// 保存key
        g_client_key = resp.data;
	  } else {
		var err = login_error[resp.header];
		if(err) {
		  alert('登录失败!('+err+')');
		} else {
		  alert('登录失败!(未知错误)');
		}
	  }
	}
  });
}

function ajax_wa() {
  //console.log(JSON.stringify(g_last_response));
  //console.log(json2str(g_last_response));
  Q.Ajax({
    command: g_server+'?app=wayixia&mod=api&action=wa&inajax=true',
    data: {img: g_last_response},
    oncomplete : function(xmlhttp) {
      // console.log(xmlhttp.responseText);
      var resp = JSON.parse(xmlhttp.responseText);
      if(resp) {
        var result = resp.header;
		if(result == 0) {
		  alert('恭喜您，成功挖到了您想要的图片!');
		} else if(result == -2) {
		  // 弹出登录界面
		  Q.$('login-area').style.display = '';
		  Q.$('image-area').style.display = 'none';
		  return;
	    }
	  } else {
	  	alert('哎呀，挖一下，失败了!('+resp.data+')')
	  }
	  CloseDialog(true);
    }
  });
}

function CloseDialog(success) {
  chrome.extension.sendRequest({
      type: "forward",
      request: {
        type: "click-close",
        remove: (typeof success == "boolean" ? success : false)
      }
    }
  );
}


/**
 * Returns a function which will handle displaying information about the
 * image once the image has finished loading.
 */
function getImageInfoHandler(url) {
  
  return function() {
	var img = this;	
	Q.$('button-ok').disabled = false;
	g_last_response.width = img.width;
	g_last_response.height = img.height;
	/// alert(this.width + '/' + this.height);
	var image_area = Q.$('image-area');
	//alert(image_area.style.width);
	var image_area_width = 266;
	var image_area_height = (img.height * image_area_width) / (img.width*1.0);    
	image_area.style.height = image_area_height + 'px';
	//alert(image_area_width + ' / ' + image_area_height);
	Q.render('autofit')('af', 'thumb');
    chrome.extension.sendRequest(
	{
	  type: "forward",
	  request: {
		  type: "ajust-dialog",
		  width: Math.max(document.body.offsetWidth || document.body.scrollWidth),
		  height: Math.max(document.body.offsetHeight || document.body.scrollHeight) + Q.$('action-bar').offsetHeight
	  }},
	  function(response) {		
		var height = response.height;
		var top = height - Q.$('action-bar').offsetHeight;
		Q.$('action-bar').style.left = 0;
		Q.$('action-bar').style.top = top + 'px';
	});
  };
};

Q.Ready(function(){

  var button_ok = Q.$('button-ok');
  button_ok.hideFocus = true;
  button_ok.disabled = true;
  button_ok.onclick=AddImage();

  var button_cancel = Q.$('button-cancel');
  button_cancel.hideFocus = true;
  button_cancel.onclick=function() { CloseDialog(false);  };

  Q.$('login-area').style.display='none';
  Q.$('login-forgetpwd').href=g_server+'?app=wayixia&mod=user&action=forgetpwd';
  Q.$('login-forgetpwd').target = '_blank';
  Q.$('login-register').href=g_server+'?app=wayixia&mod=user&action=register';
  Q.$('login-register').target = '_blank';

  chrome.extension.sendRequest( {
    type: "forward",
    request: {
      type: "init-dialog"
    }
  }, 
  function(response) {
	g_last_response = response;
	Q.$('image-area').onload = getImageInfoHandler(response.srcUrl);
	Q.$('image-area').onerror = function() { alert('受保护限制，无法挖取.'); }
	Q.$('image-area').src = response.srcUrl;
	
  });
});



